<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTenantsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tenants', function (Blueprint $table) {
            $table->id()->comment('租户主键ID');
            $table->string('name')->unique()->comment('租户名称');
            $table->string('contact_phone')->unique()->comment('联系电话');
            $table->string('contact_email')->unique()->comment('联系邮箱');
            $table->enum('tenant_type', ['individual', 'enterprise'])->default('individual')->comment('租户类型：individual个人，enterprise企业');
            $table->decimal('account_balance', 15, 2)->default(0)->comment('账户余额');
            $table->decimal('invoiceable_amount', 15, 2)->default(0)->comment('可开票金额');
            $table->string('domain')->unique()->comment('租户域名');
            $table->string('database')->nullable()->comment('租户数据库名（如果使用数据库分离）');
            $table->json('settings')->nullable()->comment('租户配置信息');
            $table->enum('status', ['active', 'inactive', 'suspended'])->default('active')->comment('租户状态：active激活，inactive停用，suspended暂停');
            $table->unsignedBigInteger('created_by')->nullable()->comment('创建人（A端用户ID）');
            $table->timestamp('created_at')->useCurrent()->comment('创建时间');
            $table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate()->comment('更新时间');

            // 外键
            $table->foreign('created_by')->references('id')->on('admin_users')->onDelete('set null');

            // 索引
            $table->index(['tenant_type']);
            $table->index(['created_by']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tenants');
    }
}
